/**
 * 代理服务
 */
const express = require('express');
const request = require('request');
const path = require('path'); // 系统路径模块
const fs = require('fs'); // 文件模块
const chalk = require('chalk');// 控制台输出颜色

// 配置信息
const config = require('../config.js');

// 初始化路由,设定项目初始页面
const router = express.Router();
router.get('/', (req, res, next) => {
  res.sendfile('./index.html');
});

const app = express();
app.use('/', router);

// 静态资源,没有代理走路由
const statics = [
  { router: '/index.html' },
  { router: '/dist' },
  { router: '/config-app' },
  { router: '/public' },
  { router: '/static' },
  { router: '/js' },
  { router: '/lib' },
  { router: '/view' },
];

statics.map((item) => {
  app.use(item.router, express.static(path.resolve(__dirname, '../../', `./${(item.proxy || item.router)}`)));
});

// 本地测试数据
const datas = [
  { router: '../config.json' },
];
datas.map((item) => {
  app.use(item.router, (req, res) => {
    console.log(chalk.green(req.originalUrl));
    const url = req.originalUrl.split('?')[0];
    const file = path.join(__dirname, url); // 文件路径，__dirname为当前运行js文件的目录
    // 读取json文件
    fs.readFile(file, 'utf-8', (err, data) => {
      if (err) {
        res.send('{success:false,obj:"文件读取失败"}');
      } else {
        res.send(data);
      }
    });
  });
});

// 路由代理
const serverUrl = config.proxyServerUrl;
const rbacUrl = config.proxyRbacUrl;
const routers = [
  { router: '/rbac', folder: 'RBAC', proxy: rbacUrl }, // 登录rbac
  { router: '/', folder: 'SERVER', proxy: serverUrl }, // 数据请求
];
routers.map((item) => {
  if (item.proxy) {
    const _router = item.router; // 路由
    const { folder } = item; // 目录描述
    const { proxy } = item; // 代理
    app.use(_router, (req, res, next) => {
      if (_router == '/' || req.baseUrl == _router) {
        let url = proxy + _router + req.url;
        if (_router == '/') {
          url = proxy + req.url;
          console.log(chalk.gray(`[${folder}] ${proxy}`) + req.url);
        } else {
          console.log(chalk.gray(`[${folder}] ${proxy}`) + _router + req.url);
        }

        // 如果请求出错，404
        req.pipe(request(url)).on('error', (err) => {
          console.log(chalk.red(`[Error] ${err.message}`));
          console.log(chalk.red(url));
          res.status(404).end();
        }).pipe(res);
      } else {
        next();
      }
    });
  }
});

// webpack打包文件
require('../webpack/webpack.js');
// 启动服务
app.listen(config.serverPort, config.server, () => { // 前端ajax地址写 http://localhost:3000/
  console.log('');
  console.log(`本地服务已启动，请访问：${chalk.green(`http://localhost:${config.serverPort}`)}`);
  console.log('');
});
